import type { Recordable, UserInfo } from '@vben/types';

import { ref } from 'vue';
import { useRouter } from 'vue-router';

import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';
import { resetAllStores, useAccessStore, useUserStore } from '@vben/stores';

import { notification } from 'ant-design-vue';
import { defineStore } from 'pinia';
import { sm2 } from 'sm-crypto-v2';

import { logoutApi } from '#/api'; // loginApi,getUserInfoApi
import { getUserInfoApi, loginApi } from '#/api/system';
import { $t } from '#/locales';

export const useAuthStore = defineStore('auth', () => {
  const accessStore = useAccessStore();
  const userStore = useUserStore();
  const router = useRouter();

  const loginLoading = ref(false);

  /**
   * 异步处理登录操作
   * Asynchronously handle the login process
   * @param params 登录表单数据
   */
  async function authLogin(
    params: Recordable<any>,
    onSuccess?: () => Promise<void> | void,
  ) {
    // 异步处理用户登录操作并获取 accessToken
    let userInfo: null | UserInfo = null;
    try {
      loginLoading.value = true;
      // SM2加密密码
      const publicKey = import.meta.env.VITE_GLOB_SM_PUBLIC_KEY;
      const password = sm2.doEncrypt(params.password, publicKey, 1);

      params.password = password;

      const { accessToken } = await loginApi(params);

      // 如果成功获取到 accessToken
      if (accessToken) {
        accessStore.setAccessToken(accessToken);

        // 获取用户信息并存储到 accessStore 中
        const fetchUserInfoResult = await fetchUserInfo();

        userInfo = fetchUserInfoResult;
        const accessCodes = userInfo?.buttons ?? [];
        userStore.setUserInfo(userInfo);
        accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          onSuccess
            ? await onSuccess?.()
            : await router.push(userInfo.homePath || DEFAULT_HOME_PATH);
        }

        if (userInfo?.realName) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.realName}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
        console.log('1');
        //存储字典信息到浏览器缓存
        var dictList = await getAllDictList();
        var dictListTemp = JSON.parse(JSON.stringify(dictList));

        await Promise.all(
          Object.keys(dictList).map(async (key) => {
            dictList[key].forEach((da: any, index: any) => {
              setDictLangMessageAsync(dictListTemp[key][index]);
            });
            // 如果 key 以 "Enum" 结尾，则转换 value 为数字
            if (key.endsWith('Enum')) {
              dictListTemp[key].forEach(
                (e: any) => (e.value = Number(e.value)),
              );
            }
          }),
        );
        localStorage.setItem('dictList', JSON.stringify(dictListTemp));
      }
    } finally {
      loginLoading.value = false;
    }

    return {
      userInfo,
    };
  }

  async function logout(redirect: boolean = true) {
    try {
      await logoutApi();
    } catch {
      // 不做任何处理
    }
    resetAllStores();
    accessStore.setLoginExpired(false);

    // 回登录页带上当前路由地址
    await router.replace({
      path: LOGIN_PATH,
      query: redirect
        ? {
            redirect: encodeURIComponent(router.currentRoute.value.fullPath),
          }
        : {},
    });
  }

  async function fetchUserInfo() {
    let userInfo: null | UserInfo = null;
    userInfo = await getUserInfoApi();
    userStore.setUserInfo(userInfo);
    return userInfo;
  }

  function $reset() {
    loginLoading.value = false;
  }

  // 处理字典国际化, 默认显示字典中的label值
  const setDictLangMessageAsync = async (dict: any) => {
    dict.langMessage = `dictType.${dict.typeCode}_${dict.value}`;
    const text = $t(dict.langMessage);
    dict.label = text !== dict.langMessage ? text : dict.label;
  };

  return {
    $reset,
    authLogin,
    fetchUserInfo,
    loginLoading,
    logout,
  };
});
